package com.example.demo.hystrix;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;


public class GetCourseHystrixCommand extends HystrixCommand<String> {
    private CourseService courseService;

    protected GetCourseHystrixCommand(CourseService courseService) {
        super(setter());
        this.courseService= courseService;
    }

    @Override protected String run() throws Exception {
        return courseService.getCourse();
    }

    @Override
    protected String getFallback(){
        return "getFallback HystrixCommand course.";
    }

    private static Setter setter(){
        HystrixCommandGroupKey commandGroupKey= HystrixCommandGroupKey.Factory.asKey("course");
        HystrixCommandProperties.Setter commandProperties= HystrixCommandProperties.Setter()
                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
                .withFallbackEnabled(true)//是否启用降级
                .withFallbackIsolationSemaphoreMaxConcurrentRequests(10)//设置getFallback并发请求信号量，如果超过信号量值，不会再走直getFallback而直接快速失败
                .withExecutionIsolationThreadInterruptOnFutureCancel(true)
                .withExecutionIsolationThreadInterruptOnTimeout(true)//当隔离策略为Thread时候，当线程超时时，是否中断处理
                .withExecutionTimeoutEnabled(true)//是否启用超时机制
                .withExecutionTimeoutInMilliseconds(2000);//超时时间设置
        return HystrixCommand.Setter.withGroupKey(commandGroupKey)
                .andCommandPropertiesDefaults(commandProperties);
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        GetCourseHystrixCommand courseHystrixCommand= new GetCourseHystrixCommand(new CourseService());
        Future<String> future= courseHystrixCommand.queue();
        System.out.println(future.get());
    }
}
